package com.dai.yygh.cmn.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dai.yygh.cmn.listener.DictListener;
import com.dai.yygh.cmn.mapper.DictMapper;
import com.dai.yygh.cmn.service.DictService;
import com.dai.yygh.model.cmn.Dict;
import com.dai.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;


    //@Cacheable 先查询是否有缓存如果有就读缓存，如果没有就生成空间为“dict”的缓存
    @Override
    public List<Dict> findChildData(Long id) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId,id);
        //所有子id的数量
        List<Dict> list = dictMapper.selectList(queryWrapper);
        //判断是否有子节点
        for (Dict dict : list) {
            Long id1 = dict.getId();
            boolean children = this.isChildren(id1);
            dict.setHasChildren(children);
        }
        return  list;
    }


    //导出就等于是下载操作
    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置下载信息
        //设置content类型
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName= "dict";
        //content-disposition 这个头信息就是告诉我们以下载方式打开
        response.setHeader("content-disposition","attachment;filename"+fileName+".xlsx");


        //查询数据库
        List<Dict> list = dictMapper.selectList(null);
        //调用方法进行写操作
        try {
            //out 是写，然后选择写的类，名字，然后数据
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("dict")
                    .doWrite(copyList(list));
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //缓存 把空间为“dict”的缓存下的内容清空
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener())
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //查询名称
    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空,直接根据value查询
        if(StringUtils.isEmpty(dictCode)){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("value",value);
            Dict dict = dictMapper.selectOne(queryWrapper);
            return dict.getName();
        }else{//如果dictCode不为空,根据dictCode和value查询
            //根据dictcode查询dict对象，目的是得到dict的id值，在根据此id值查询此id下的子id
            QueryWrapper<Dict> queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("dict_code",dictCode);
            Dict codeDict = dictMapper.selectOne(queryWrapper1);
            Long parent_id = codeDict.getId();
            //根据parentId和value值进行查询
            QueryWrapper<Dict> queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("parent_id",parent_id).eq("value",value);
            Dict finalDict = baseMapper.selectOne(queryWrapper2);
            return finalDict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

        LambdaQueryWrapper<Dict> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getDictCode,dictCode);
        Dict dict = dictMapper.selectOne(queryWrapper);
        Long id = dict.getId();

        queryWrapper.clear();
        queryWrapper.eq(Dict::getParentId,id);
        List<Dict> list = dictMapper.selectList(queryWrapper);

        return list;
    }


    private List<DictEeVo> copyList(List<Dict> list) {
        List<DictEeVo> dictEeVoList=new ArrayList<>();
        for (Dict dict : list) {
            DictEeVo dictEeVo= copy(dict);
            dictEeVoList.add(dictEeVo);
        }
        return dictEeVoList;
    }

    private DictEeVo copy(Dict dict) {
        DictEeVo dictEeVo=new DictEeVo();
        BeanUtils.copyProperties(dict,dictEeVo);
        return dictEeVo;
    }


    private boolean isChildren(Long id){
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId,id);
        Integer integer = dictMapper.selectCount(queryWrapper);
        return integer>0;
    }

}
